package com.ai_daily.aitiantian.api.converter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class FlexibleDataResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    FlexibleDataResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            // 检查是否以 "data:" 开头
            if (response.startsWith("data:")) {
                // 去掉前缀 "data:" 并修剪
                response = response.replace("data:", "").trim();
            }
            // 使用Gson解析剩余的JSON字符串
            return adapter.fromJson(response);
        } finally {
            value.close();
        }
    }

}